<?php

class LoginController extends Zend_Controller_Action
{

   public function init()
    {
        /* Initialize action controller here */
    }
 
    public function indexAction()
    {
        $loginForm = new Form_Login();
        
       //checkout whether the user is already logged in or not.
        if (Zend_Auth::getInstance()->hasIdentity()) {
              // $this->_forward("index","index");
               $this->_redirect("index/index");
        }
        else {
            if ($this->getRequest()->isPost()) {
                if ($loginForm->isValid($this->getRequest()->getPost())) {
                    $username = $this->getRequest()->getPost('userName');
                    $password = $this->getRequest()->getPost('password');

                    $dbAdapter = Zend_Db_Table::getDefaultAdapter();
                    $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

                    $authAdapter->setTableName('users')
                                ->setIdentityColumn('Username')
                                ->setCredentialColumn('Password')
                                ->setCredentialTreatment('MD5(?)')
                                ->setIdentity($username)
                                ->setCredential($password);

                    $auth = Zend_Auth::getInstance();
                    $result = $auth->authenticate($authAdapter);

                    // is the user a valid one?
                    if($result->isValid()) {
                        // get all info about this user from the login table
                        // ommit only the password, we don't need that
                        $userInfo = $authAdapter->getResultRowObject(null, 'password');

                        // the default storage is a session with namespace Zend_Auth
                        $authStorage = $auth->getStorage();
                        $authStorage->write($userInfo);

                        $this->_redirect('index/index');
                    }
                    else {
                        $errorMessage = "Wrong username or password provided. Please try again.";
                    }
                    
                    $this->view->errorMessage = $errorMessage;
                    $this->view->loginForm = $loginForm;
                }
            }
        }
        $this->view->loginForm = $loginForm;
    }
 }